#!/bin/bash

# Web Notes 问题排查脚本
echo "🔧 Web Notes 问题排查工具"
echo "=================================="

# 获取服务器IP
SERVER_IP=$(hostname -I | awk '{print $1}')

echo "服务器IP: $SERVER_IP"
echo ""

# 检查常见问题
echo "1. 检查API URL问题"
echo "==================="

# 模拟前端请求
echo "模拟登录请求测试..."
curl -X POST http://localhost/api/auth/login \
     -H "Content-Type: application/json" \
     -d '{"email":"test@test.com","password":"test123"}' \
     -v 2>&1 | head -20

echo ""
echo "2. 检查服务状态"
echo "==============="

# PM2状态详细信息
echo "PM2详细状态:"
pm2 show web-notes-api 2>/dev/null || echo "❌ web-notes-api 服务未找到"

echo ""
echo "3. 检查端口占用"
echo "==============="
echo "端口占用情况:"
ss -tlnp | grep -E "(3000|80)"

echo ""
echo "4. 检查防火墙"
echo "============="
if command -v ufw &> /dev/null; then
    echo "UFW状态:"
    ufw status
elif command -v firewalld &> /dev/null; then
    echo "Firewalld状态:"
    firewall-cmd --list-all
else
    echo "未检测到防火墙管理工具"
fi

echo ""
echo "5. 检查最近的错误日志"
echo "===================="

echo "Nginx错误日志 (最近10行):"
if [ -f "/var/log/nginx/web-notes-error.log" ]; then
    tail -10 /var/log/nginx/web-notes-error.log
else
    echo "❌ Nginx错误日志文件不存在"
fi

echo ""
echo "PM2错误日志 (最近10行):"
pm2 logs web-notes-api --lines 10 --err 2>/dev/null || echo "❌ 无法获取PM2日志"

echo ""
echo "6. 网络连通性测试"
echo "=================="

echo "测试后端直连:"
timeout 5 curl -s http://localhost:3000/health && echo " ✅ 后端直连成功" || echo " ❌ 后端直连失败"

echo "测试Nginx代理:"
timeout 5 curl -s http://localhost/api/health && echo " ✅ Nginx代理成功" || echo " ❌ Nginx代理失败"

echo "测试外部访问:"
timeout 5 curl -s http://$SERVER_IP/api/health && echo " ✅ 外部访问成功" || echo " ❌ 外部访问失败"

echo ""
echo "7. 建议的修复步骤"
echo "=================="

# 分析问题并给出建议
if ! pm2 list | grep -q "web-notes-api.*online"; then
    echo "❌ 后端服务未运行"
    echo "   修复: pm2 start /var/www/web-notes/web-notes-backend/dist/index.js --name web-notes-api"
fi

if ! netstat -tlnp | grep -q ":3000"; then
    echo "❌ 3000端口未监听"
    echo "   检查后端服务是否正常启动"
fi

if ! curl -s http://localhost/api/health > /dev/null; then
    echo "❌ Nginx代理配置问题"
    echo "   检查: nginx -t"
    echo "   重载: systemctl reload nginx"
fi

if [ ! -f "/var/www/html/index.html" ]; then
    echo "❌ 前端文件缺失"
    echo "   重新部署前端文件到 /var/www/html/"
fi

echo ""
echo "🔧 完整重新部署命令:"
echo "sudo ./redeploy-fixed.sh"

echo ""
echo "排查完成！"